package com.brtbeacon.wx.demo.mapview;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import okhttp3.HttpUrl;

public class MapListActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    public final static int CODE_REQUEST_PERMISSIONS = 999;
    public final static int REQUEST_CODE_ADD = 1;

    private List<MapRecord> defaultMapList = new ArrayList<>();

    private ListView listView;
    private ArrayAdapter<MapRecord> mapRecordAdapter;
    private List<MapRecord> mapRecordList = new ArrayList<>();
    private CheckBox cboxCustomWebView;

    private MapRecordDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_list);
        db = new MapRecordDatabase(this);
        cboxCustomWebView = findViewById(R.id.cbox_custom);
        findViewById(R.id.btn_add).setOnClickListener(this);
        listView = findViewById(R.id.listView);
        mapRecordAdapter = new ArrayAdapter<MapRecord>(this, android.R.layout.simple_list_item_2, android.R.id.text1, mapRecordList) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View rootView = super.getView(position, convertView, parent);
                TextView tvName = rootView.findViewById(android.R.id.text1);
                TextView tvURL = rootView.findViewById(android.R.id.text2);
                MapRecord record = getItem(position);
                tvName.setText(record.name);
                tvURL.setText(record.url);
                return rootView;
            }
        };
        listView.setAdapter(mapRecordAdapter);

        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);

        reloadMapRecords();
        checkPermissions();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add: {
                Intent intent = new Intent(this, MapAddActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD);
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADD) {
                MapRecord record = new MapRecord();
                record.name = data.getStringExtra("name");
                record.url = data.getStringExtra("url");
                db.addMapRecord(record);
                reloadMapRecords();
            }
        }
    }

    private void reloadMapRecords() {
        mapRecordList.clear();
        mapRecordList.addAll(MapConstants.getDefaultMaps());
        mapRecordList.addAll(db.getMapRecords());
        mapRecordAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MapRecord record = (MapRecord) parent.getItemAtPosition(position);
        String url = getAppendURL(record.url);
        if (TextUtils.isEmpty(url))
            return;

        if (cboxCustomWebView.isChecked()) {
            CustomWebViewActivity.startActivity(this, url);
        } else {
            MyDefaultWxMapActivity.startActivity(this, url);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final MapRecord record = (MapRecord) parent.getItemAtPosition(position);
        if (record.id < 0)
            return false;

        new AlertDialog.Builder(this)
                .setMessage("是否删除该地图数据?")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        db.removeMapRecord(record.id);
                        reloadMapRecords();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .create().show();
        return true;
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            String[] permissions = new String[] {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            };

            List<String> checkPermissionList = new ArrayList<>();

            for (String permission: permissions) {
                if (this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    checkPermissionList.add(permission);
                }
            }

            if (!checkPermissionList.isEmpty()) {
                requestPermissions(checkPermissionList.toArray(new String[1]), CODE_REQUEST_PERMISSIONS);
            }
        }
    }

    //  给链接中添加当前设备IMEI标识；
    private String getAppendURL(String url) {
        /*
        TelephonyManager telManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "缺少获取设备唯一标识的权限!", Toast.LENGTH_SHORT).show();
            return "";
        }

        String imei = telManager.getDeviceId();


        if (TextUtils.isEmpty(imei)) {
            Toast.makeText(this, "无法获取设备唯一标识!", Toast.LENGTH_SHORT).show();
            return "";
        }

        try {
            HttpUrl httpUrl = HttpUrl.parse(url);
            httpUrl = httpUrl.newBuilder().addQueryParameter("mac", imei).build();
            return httpUrl.toString();
        } catch (Exception e){
            Toast.makeText(this, "H5地址无效，请重新输入!", Toast.LENGTH_SHORT).show();
        }
        */

        return url;
    }
}
